package com.longxi.tianjintianbao.ui.presenter.patrol;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataPatrolController;
import com.longxi.tianjintianbao.greedao.entity.Patrol;
import com.longxi.tianjintianbao.ui.activity.patrol.PatrolScanSearchActivity;
import com.longxi.tianjintianbao.ui.activity.scan.ScanActivity;
import com.longxi.tianjintianbao.ui.adapter.PatrolListPagerAdapter;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.fragment.patrol.PatrolListFragment;
import com.longxi.tianjintianbao.ui.view.patrol.IPatrolListAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetworkUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PatrolListAtPresenter extends BasePresenter<IPatrolListAtView> {

    private PatrolListPagerAdapter patrolListPagerAdapter;
    private Intent intent = new Intent();
    public long count = 0;//有多少未上传数据

    private void initVariable() {
        mCategoryList = new ArrayList<>();
        mCategoryList.add("待巡检");
        mCategoryList.add("未提交");
        mCategoryList.add("已提交");
        mCategoryList.add("逾期未巡检");
    }

    //tab 标签页
    private List<String> mCategoryList;

    public List<String> getCategoryList() {
        if (mCategoryList == null) {
            mCategoryList = new ArrayList<>();
        }
        return mCategoryList;
    }

    public PatrolListAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("巡检");
        mContext.setTvLeft(MyUtils.getString(R.string.home));
        mContext.setIvRight(R.mipmap.ic_scan);
        setUINoUploadData();
        initVariable();
    }

    /**
     * 更新一下数据 并且将上传数据按钮显示出来
     */
    public void setUINoUploadData() {
        count = DataPatrolController.isUploadData();
        if(count > 0){
            mContext.setIvRight2(R.mipmap.ic_data_upload);
        }
    }

    public void initViewPager(){
        patrolListPagerAdapter = new PatrolListPagerAdapter(mContext.getSupportFragmentManager(), getCategoryList());
        getView().getViewPager().setAdapter(patrolListPagerAdapter);
        getView().getViewPager().setOffscreenPageLimit(getCategoryList().size() - 1);
        getView().getTabLayout().setViewPager(getView().getViewPager());
        getView().getTabLayout().setTabSpaceEqual(true);
        if(count != 0){
            getView().getTabLayout().showMsg(1, (int) count);
            getView().getTabLayout().setMsgMargin(1, 0, 10);
        }
    }

    public void refreshFragmentUi() {
        PatrolListFragment energyReadListFragment = (PatrolListFragment) patrolListPagerAdapter.getCurrentFragment();
        energyReadListFragment.refreshReceiptList();
        sendBroadcast();
    }

    boolean isUpload = false;

    /**
     * 如果网络正常直接上传
     * 如果网络不正常 先保存在本地
     */
    public void saveInspection() {
        if(!NetworkUtils.isAvailable(mContext)){
            MyUtils.showToast("当前网络状态不可用,已将巡检结果保留本地!");
            return;
        }

        if(isUpload){
            MyUtils.showToast("正在上传，请勿重复点击");
            return;
        }
        isUpload = true;
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        List<Patrol> patrolList = DataPatrolController.getUploadList();
        if(patrolList.size() == 0){
            mContext.hideWaitingDialog();
            MyUtils.showToast("无需要上传的数据");
            return;
        }

//        List<UploadPatrol> uploadPatrolList = new ArrayList<>();
//        Patrol patrol = patrolList.get(0);
//        uploadPatrolList.add(new UploadPatrol(patrol.getUserid(), patrol.getBillid(), patrol.getApplicant(), patrol.getState(), patrol.getExplain(), patrol.getReleasetime(), MyUtils.imageToBase64(patrol.getImage1()), MyUtils.imageToBase64(patrol.getImage2())));
        Patrol patrol = patrolList.get(0);
        org.json.JSONObject object = new org.json.JSONObject();
        try {
            object.put("userid", patrol.getUserid());
            object.put("billid", patrol.getBillid());
            object.put("applicant", patrol.getApplicant());
            object.put("state", patrol.getState());
            object.put("explain", patrol.getExplain());
            object.put("releasetime", patrol.getReleasetime());

            String image1 = "";
            String image2 = "";
            if(patrol.image1 != null){
                image1 = MyUtils.imageToBase64(patrol.image1);
            }
            if(patrol.image2 != null){
                image2 = MyUtils.imageToBase64(patrol.image2);
            }

            object.put("image1", image1);
            object.put("image2", image2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONArray jsonArray = new JSONArray();
        jsonArray.put(object);

//        for (Patrol patrol : patrolList) {
//            uploadPatrolList.add(new UploadPatrol(patrol.getUserid(), patrol.getBillid(), patrol.getApplicant(), patrol.getState(), patrol.getExplain(), patrol.getReleasetime(), MyUtils.imageToBase64(patrol.getImage1()), MyUtils.imageToBase64(patrol.getImage2())));
//        }

//        Log.d("uploadPatrol", JSONObject.toJSONString(uploadPatrolList));

        ApiRetrofit.getInstance().saveInspection(jsonArray)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
                isUpload = false;//可以上传
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                isUpload = false;//可以上传
                if(baseResponse.getCode() != 0){
                    mContext.hideWaitingDialog();
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                patrol.setIsDraft("2");
                DataPatrolController.updateIsDraftById(patrol);
                patrolList.remove(0);
                if(patrolList.size() > 0){
                    saveInspection();
                }else{
                    mContext.hideWaitingDialog();
                    setUINoUploadData();
                    getView().getTabLayout().showMsg(1, (int) count);
                    getView().getTabLayout().setMsgMargin(1, 0, 10);
                    sendBroadcast();
                    mContext.hideWaitingDialog();
                    MyUtils.showToast("提交成功");
                }
            }
        });
    }

    /**
     * 发送广播
     */
    public void sendBroadcast(){
        //设置广播的名字（设置Action）
        intent.setAction(AppConst.REFRESH_HOME_FRAGMENT);
        //携带数据
        //intent.putExtra("refreshPatrolCount",true);
        //发送广播（无序广播）
        mContext.sendBroadcast(intent);
    }

    public void scan() {
        AndPermission.with(mContext)
        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
        .onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Intent intent = new Intent(mContext, ScanActivity.class);
                mContext.startActivityForResult(intent, AppConst.IntentRequstCode.REQUEST_CODE_SCAN);
            }
        })
        .onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                mContext.startActivity(intent);

                Toast.makeText(mContext, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
            }
        }).start();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_PATROL_DETAIL://一开始是直接能到详情页进行完成巡检操作
                saveInspection();
                refreshFragmentUi();
                setUINoUploadData();
                getView().getTabLayout().showMsg(1, (int) count);
                getView().getTabLayout().setMsgMargin(1, 0, 10);
                break;
            case AppConst.IntentRequstCode.ACTIVITY_PATROL_SCAN_SEARCH://现在只能通过扫一扫才能完成巡检单
                saveInspection();
                refreshFragmentUi();
                setUINoUploadData();
                getView().getTabLayout().showMsg(1, (int) count);
                getView().getTabLayout().setMsgMargin(1, 0, 10);
                break;
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
                if (data != null) {
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_SUCCESS) {
                            String result = bundle.getString(AppConst.RESULT_STRING);
                            String key = "XJ_";
                            if(!result.contains(key)){
                                MyUtils.showToast("该二维码不是巡检二维码");
                                return;
                            }

                            result = result.replace(key, "");
                            try {
                                LogUtils.d("二维码结果", result);
                                int a = Integer.parseInt(result);
                                Intent intent = new Intent(mContext, PatrolScanSearchActivity.class);
                                intent.putExtra(PatrolScanSearchAtPresenter.ADDRESSID, result);
                                mContext.startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_PATROL_SCAN_SEARCH);
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                                MyUtils.showToast("该二维码不是巡检二维码");
                            }
                        } else if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_FAILED) {
                            MyUtils.showToast("解析二维码失败");
                        }
                    }
                }
                break;
        }
    }
}
